<?php

@session_start();

require 'conf.php';

function error_msg($msg) 
{
    echo json_encode(array('error' => $msg));
}

function addevent($sessiontoken, $e_desc, $start, $stop, $pubshare, $etype)
{ 
    global $MW_host;
    $fields = array('USR_ADD_EVENT' => '',
                    'SESSION' => $sessiontoken,
                    'DESC' => $e_desc,
                    'START' => $start,
                    'STOP' => $stop,
                    'PUBSHARE' => $pubshare === true ? 'true' : 'false', 
                    'ETYPE' => $etype);

    $fields = http_build_query($fields);

    $h = curl_init($MW_host); 
    curl_setopt($h, CURLOPT_POST, 1);
    curl_setopt($h, CURLOPT_POSTFIELDS, $fields); 
    curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($h, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields))); 

    $res = curl_exec($h);
    if(!mb_check_encoding($res, 'UTF-8'))
        $res = utf8_encode($res);
    $data = json_decode($res);
    return $data;
}


if (!isset($_SESSION['sessiontoken'])) {
    error_msg("Ogiltig sessiontoken. Försök logga in igen.");
} else if (!isset($_POST['e_desc']) || strlen($_POST['e_desc']) < 2) {
    error_msg("Beskrivningen är för kort.");
} else if (!isset($_POST['start']) || !is_numeric($_POST['start'])) {
    error_msg("Ogiltig start tid");
} else if (!isset($_POST['end']) || !is_numeric($_POST['end'])) {
    error_msg("Ogiltig slut tid");
} else if (!isset($_POST['etype']) || strlen($_POST['etype']) < 2) {
    error_msg("Ogiltig typ");
} else if ($_POST['etype'] == 'custom' && strlen($_POST['etype-custom']) < 2) {
    error_msg("Ogiltig användardefinerad typ");
} else {
    $etype = '';
    if ($_POST['etype'] == 'custom') {
        $etype = $_POST['etype-custom'];
    } else {
        $etype = $_POST['etype'];
    }

    $res = addevent($_SESSION['sessiontoken'], $_POST['e_desc'], $_POST['start'] / 1000, $_POST['end'] / 1000, isset($_POST['pubshare']) === true, $etype);
    if ($res === null) {
        error_msg("Ett fel uppstod i komunikationen med mellan-servern");
    } else {
        echo json_encode($res);
    }
}
?>
